home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15699 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. From: Steve_Quist@msn.com (Stephen Quist)
  2. Subject: RE: Proper use of friend keyword
  3. Date: 6 Apr 96 06:12:14 -0800
  4. References: <4jn38u$j9c@holly.ACNS.ColoState.EDU>
  5. Message-ID: <00001a81+0000b164@msn.com>
  6. Path: news.msn.com!msn.com
  7. Newsgroups: comp.lang.c++
  8. Organization: The Microsoft Network (msn.com)
  9.  
  10. Corby Hudnall wrote:
  11.  
  12. Hey all, I have a question about how to use the friend keyword.  Consider
  13. the following example:
  14.  
  15. class.h---------
  16. class ABC
  17. {
  18.     int AValue;
  19.     int GetAValue() { return (AValue); }
  20. public:
  21.     ABC() { AValue=5; }
  22.     ~ABC(){ }
  23. };
  24.  
  25. class XYZ
  26. {
  27. public:
  28.     XYZ() { }
  29.     ~XYZ() { }
  30.     friend int ABC::GetAValue();
  31. };
  32.  
  33. prog.C--------------------
  34. #include <iostream.h>
  35. #include "class.h"
  36.  
  37. void main()
  38. {
  39.   ABC abc;
  40.   XYZ xyz;
  41.  
  42.   cout << xyz.GetAValue() << endl
  43. }
  44.  
  45.  
  46. when I try to compile this, I get the message "no member funciton 
  47. 'XYZ::GetAValue()' defined."  What do I need to do in order to 
  48. make this work.  Thanks for any and all suggestions.
  49. -----------------
  50. Well, the compiler is of course right. I am not sure what you are
  51. trying to do. If you are trying to make GetAValue() a mf of XYZ
  52. then ABC and XYZ should have an inheritance relationship. The
  53. friend relationship means that ABC::GetAValue() can access the
  54. private parts of an XYZ object. To flesh it out a little bit lets
  55. give XYZ some private data.
  56.  
  57. class.h---------
  58. class XYZ; // forward declaration
  59. class ABC
  60. {
  61.     int AValue;
  62.     int GetAValue(XYZ &t) { return (AValue * t.private_member); }
  63. public:
  64.     ABC() { AValue=5; }
  65.     ~ABC(){ }
  66. };
  67.  
  68. class XYZ
  69. {
  70. public:
  71.     XYZ() :private_member(2) { }
  72.     ~XYZ() { }
  73.     friend int ABC::GetAValue();
  74. private:
  75.     int private_member;
  76. };
  77.  
  78. Now ABC::GetAValue(XYZ&) has friend access to XYZ
  79.  
  80. Hope this helps
  81. Steve Quist
  82.